/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;

/**
 * GroupsAnnouncementActivity </p> 客户 2014-5-20 上午11:21:00 create
 * 
 * @since 1.0
 */
public class GroupsContactListActivity extends Activity {
	private final String TAG = "GroupsAnnouncementActivity";
	private Context mContext;
	private Groups mGroups;
	private String user_id = "";
	private String token = "";
	private ArrayList<Projects> mProjectsList;
	private PageProjectAdapter mRuAdapter2;
	private PullToRefreshListView firstcategory2 = null;
	private ListView actualListView2 = null;
	private int scrollTopBottompr = 0;
	private int pageIndexpr = 1;
	private int contactLastPos = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_project);
		mContext = this;
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, "");
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title = (TextView) findViewById(R.id.xm_bi_tv_title);
		if (intent.getExtras() != null) {
			mGroups = (Groups) intent.getExtras().getSerializable("groupsMain");
		}
		xm_bi_tv_title.setText("客户");
		if (mGroups != null) {
			getProjects(1);
		}
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		firstcategory2 = (PullToRefreshListView) findViewById(R.id.firstcategoryXM);
		firstcategory2.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (scrollTopBottompr == 1) {
					pageIndexpr++;
					if (mGroups != null) {
						getProjects(pageIndexpr);
					}
				} else if (scrollTopBottompr == 0) {
					pageIndexpr = 1;
					if (mGroups != null) {
						getProjects(pageIndexpr);
					}
				}
			}
		});

		firstcategory2.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					contactLastPos = firstcategory2.getRefreshableView()
							.getLastVisiblePosition();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					scrollTopBottompr = 1;
				} else if (firstVisibleItem == 0) {
					scrollTopBottompr = 0;
				}
				System.out.println("=========" + scrollTopBottompr);
			}
		});
		actualListView2 = firstcategory2.getRefreshableView();
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (content != null && content.trim().equals("用户不存在")) {
							// finish();
						}
						if ("登陆失效，需重新登陆".equals(content)
								|| "join(f.username.errors)".equals(content)) {
							LoginUtil.executeLoginFaild(mContext);
						}

					}
				}).show();
	}

	/**
	 * 获取客户数据
	 * 
	 * @param pageIndex
	 */
	private void getProjects(final int pageIndex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			// http://crmsoap.woniuwo.cn/clients_of_group?group_id=5374724ed5ac700e4ce8f609&user_id=cd34350bb2844077bfbd4abe5ec56f99
			// &token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl&page=1
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");

			String URL = Network.API_DOMAIN + "/clients_of_group?group_id="
					+ mGroups.getGroup_id() + "&user_id=" + user_id + "&token="
					+ token + "&validation=" + CRMUserBaseInfo.kValication
					+ "&page=" + pageIndex;

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("获取客户数据  response=" + response);
							try {
								String user_id = "";
								String token = "";
								Log.e("wop",
										" response = " + response.toString());
								if (!response.isNull("clients")) {
									String myString = response.get("clients")
											.toString();
									if (myString.equals("[]")) {
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										if (mProjectsList == null
												|| pageIndex == 1) {
											mProjectsList = new ArrayList<Projects>();
										}
										jsonArr = response
												.getJSONArray("clients");
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
													.length(); i++) {
												Projects my_project = new Projects();
												JSONObject jsonObj2 = jsonArr
														.getJSONObject(i);
												if (!jsonObj2
														.isNull("client_id")) {
													String client_id = jsonObj2
															.getString("client_id");
													my_project
															.setClient_id(client_id);
												}
												if (!jsonObj2
														.isNull("chinese_name")) {
													String chinese_name = jsonObj2
															.getString("chinese_name");
													my_project
															.setProject_name(chinese_name);
												}
												mProjectsList.add(my_project);
											}
										}
										if (!response.isNull("errors")) {
											String errors = response.get(
													"errors").toString();
											if (errors.equals("[]")) {
											} else {
												org.json.JSONArray jsonArrs;
												if (!response.isNull("errors")) {
													LoginError mLoginError = new LoginError();
													jsonArrs = response
															.getJSONArray("errors");
													if (jsonArrs.length() > 0) {
														for (int i = 0; i < jsonArrs
																.length(); i++) {
															JSONObject jsonObj2 = jsonArrs
																	.getJSONObject(i);
															if (!jsonObj2
																	.isNull("desc")) {
																// dismissProgressDialog(progressDialog);
																String desc = jsonObj2
																		.getString("desc");
																openDailog(
																		"登录失败提示",
																		desc);
																mLoginError
																		.setDesc(desc);
															}
															if (!jsonObj2
																	.isNull("value")) {
																String value = jsonObj2
																		.getString("value");
																mLoginError
																		.setValue(value);
															}
														}
													}
												}
											}
										}
										mRuAdapter2 = new PageProjectAdapter(
												mContext, mProjectsList);
										mRuAdapter2.notifyDataSetChanged();
										actualListView2.setAdapter(mRuAdapter2);
										if (pageIndex > 1) {
											actualListView2
													.setSelection(contactLastPos);
										}
									}
									if (firstcategory2 != null) {
										firstcategory2.onRefreshComplete();
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}

}

class PageProjectAdapter extends BaseAdapter {
	private List<Projects> Date = null;
	private Context context;
	private LayoutInflater mInflater;
	public HashMap<Integer, Bitmap> cachedBitmap;

	private class GridHolder {
		TextView tv;
	}

	@SuppressLint("UseSparseArrays")
	public PageProjectAdapter(Context c, List<Projects> proInfoListData) {
		super();
		this.context = c;
		this.Date = proInfoListData;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public int getCount() {
		if (Date == null) {
			return 0;
		} else {
			return Date.size();
		}

	}

	@Override
	public Object getItem(int index) {
		return Date.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(final int index, View convertView, ViewGroup parent) {
		GridHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.xm_12_items, null);
			holder = new GridHolder();
			holder.tv = (TextView) convertView.findViewById(R.id.xm_12_item_tv);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}

		final String xm_txt = Date.get(index).getProject_name();
		holder.tv.setText(xm_txt);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context,
						GroupsContactListTwoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupsMain", Date.get(index));
				intent.putExtras(bundle);
				context.startActivity(intent);
			}
		});
		return convertView;
	}
}
